package p15.code;

import java.util.Random;
import java.util.concurrent.*;

import static java.util.concurrent.TimeUnit.MILLISECONDS;

public class TaskTimeStudy {

    static ExecutorService executorService = Executors.newFixedThreadPool(2);

    public static void getPage(long timeBudget) {

        long endNanos = System.currentTimeMillis() + timeBudget;//指定等待的时间

        Future<String> f = executorService.submit(()->{
            Thread.sleep(2000);
            if(new Random().nextBoolean())
                        throw new Exception("失败");
            return "广告商广告";
        });

        //在等待广告的同时显示页面
        System.out.println("页面加载");

        String ad = null;
        try{
            long timeLeft = endNanos - System.currentTimeMillis();//只等待指定时间
            ad = f.get(timeLeft,MILLISECONDS);//获取广告结果
        }
        catch(ExecutionException e){
            ad = "失败默认广告";//如果获取失败，返回默认广告
        }
        catch(TimeoutException e){//如果超时，返回默认广告，并取消这个任务
            ad = "超时默认广告";
            f.cancel(true);
        }
        catch (InterruptedException e) {
            ad = "中断默认广告";
            e.printStackTrace();
        }
        System.out.println(ad);

    }

    public static void main(String[] args) {
        getPage(2000);
    }


}
